<template>
  <div class='box-wrap'>
    <div class="tabtab">
      <el-tabs
        v-model="searchData.state"
        @tab-click="handleTabClick"
        type="card"
      >
        <el-tab-pane label="排队中" name="2"> </el-tab-pane>
        <el-tab-pane label="进行中" name="1"> </el-tab-pane>
      </el-tabs>
    </div>
    <div class='box-operation'>
      <div class="box-search">
         <div class="form-group-right-button">
          <div class='form-group-enquire' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg" title="点击刷新"></div>
          <el-dropdown>
            <div class='form-group-enquire-flash' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/flash.svg" title="点击刷新"></div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>自动刷新<el-switch
                  v-model="flashvalue"
                  @change="flashSettimeout()"
                  active-color="#13ce66">
                </el-switch></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
         </div>
         <el-dialog
          :visible.sync="dialogVisible"
          title="定时时长"
          width="30%" class="diacls">
          <el-input v-model="dialogVisibleInput" ></el-input>秒
            <el-button type="primary" @click="dialogVisibleON()">确 定</el-button>
        </el-dialog>
        <!-- <div class='form-group-addimg' @click='downloadFile()'><img src="../../assets/images/peach-svg/export.svg"></div>
        <div class="form-group-right-button">
          <div class='form-group-enquire'  @click='addSieveOpen2(3)'><img src="../../assets/images/peach-svg/export_list.svg"></div>
          <div class='form-group-enquire'  @click='addSieveOpen2(2)'><img src="../../assets/images/peach-svg/export_pl.svg"></div>
        </div> -->
      </div>
    </div>
    <LibVxeTable class="staticData"
      :tableColumns="tableColumns"
      :tableData="list"
      :slotHeader="slotHeader"
      border="none"
      :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size,pageSizes:[30, 50, 100,1000]}"
      @onPageChange="onChangePageSize"
      @onSelectChange="onCheckChange"
      :stripe="false"
      :footer-method="footerMethodFunc"
      resizable>
     </LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from "@/commons/staticName";
import bus from "@/commons/EventBus";

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      dialogVisible:false,
      dialogVisibleInput:5,
      diatiemr:5,
      statuslist:[],
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        page_index:1,
        page_size:30,
        state:"2" ,
        detail:1,
      },
      _date:'',
      flashvalue: false,
      timer:'',
      Dus:"",//单个下载还是多个
      task_number:"",
      valid_number:'',  
      status_list:[{id:1,name:"进行中"},{id:3,name:"已停止"},{id:4,name:"已完成"}],
      warehouse_obj:{ 1:"WS",2:"FB",3:"INS",4:"Amazon",5:"Linkedin",6:"Viber",7:"Line",8:"Zalo",9:"Twitter",
      10:"Skype",11:"TG",12:"momo",13:"MtnMOMO",14:"微软账号",15:"TrueMoney",16:"BOTIM",17:"运营商",18:"空号检测",19:"TK"},
      time_at:"",
      time_mouth:"",
      selectRows:[],
      countrylist:[],
      sourcelist:[],
      countrylistObj:{},
      list:[],
      totalCnt:0,
      info:{},
      tableColumns:[
        {
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "任务ID",
          field: "id",
          align: 'center',
        },
        
        {
          title: "业务类型",
          field: "operator",
          align: 'center',
          // slots:{
          //   default: ({row},h) => {
          //     return this.$AutoFun(()=>{
          //     let reserse2=this.warehouse_obj[row.warehouse_type]
          //     return [ h("div",reserse2)];
          //   });
          //   }
          // }
        },
        {
          title: "国家",
          field: "country",
        },
        {
          title: "任务数",
          field: "task_count",
          align: 'center',
        },
         {
          title: "有效数",
          field: "valid_count",
          align: 'center',
        },
         {
          title: "已完成数",
          field: "finish_count",
          align: 'center',
        },
        // {
        //   title: "权重",
        //   field: "country1",
        //   slots:{
        //     default: ({rowIndex},h) => {
        //       return [ h("div",rowIndex)];
        //     }
        //   }
        // },
        {
          title: "状态",
          field: "state",
          align: 'center',
          // width:150,
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
              // if(row.state !== 2){
                hButton.push(h(
                   "div",
                    {
                      class:row.state=="init"?"eight":row.state=="run"?"four":row.state=="pause"?"five":row.state=="terminate"?"six":row.state=="finish"?"seven":"seven",
                    },
                  ));
              return hButton;
            });
            }
          }
        },
        {
          title: "持续时长",
          field: "elapsed_time",
          align: 'center',
        },
        {
          title: "开始时间",
          field: "create_at",
          align: 'center',
          width:  130,
          slots: {
            default: ({row},h) => {
                const _date = row.create_at.slice(0,10)
                const _time = row.create_at.slice(11,19)
                 return [h("div",_date+" "+_time)];
            }
          }
        },
        {
          title: "更新时间",
          field: "update_at",
          align: 'center',
          width:  130,
          slots: {
            default: ({row},h) => {
                const _date = row.update_at.slice(0,10)
                const _time = row.update_at.slice(11,19)
                 return [h("div",_date+" "+_time)];
            }
          }
        },
        {
          title: "操作",
          field: "action",
          align: "center",
          width:300,
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
              // let optitle=''
              // let opjiekou=''
              // if(row.state=='pause')
              // {
              //   optitle="启动"
              //   opjiekou='start'
              // }else if(row.state=='run'){
              //   optitle='暂停'
              //   opjiekou='pause'
              // }
              //   if(row.state=="pause"||row.state=="run"){
                  hButton.push(
                    h(
                      "el-button",
                      {
                        props: { type: "success", size: "small" },
                        style: { marginRight: "5px",backgroundColor:"#3DD598" ,borderColor:"#3DD598"},
                        on: {
                          click: () => {
                            this.addWarehouse2(4,row,'start','启动');
                          }
                        }
                      },
                      "启动"
                    )
                  );
                  hButton.push(
                    h(
                      "el-button",
                      {
                        props: { type: "success", size: "small" },
                        style: { marginRight: "5px",backgroundColor:"#3DD598" ,borderColor:"#3DD598"},
                        on: {
                          click: () => {
                            this.addWarehouse2(3,row,'pause','暂停');
                          }
                        }
                      },
                      "暂停"
                    )
                  );
                // }
                hButton.push(
                  h(
                    "el-button",
                    {
                      props: { type: "success", size: "small" },
                      style: { marginRight: "5px" },
                      on: {
                        click: () => {
                          this.addWarehouse2(2,row,"terminate",'终止');
                        }
                      }
                    },
                    "终止"
                  )
                );
                // if(!this.searchData.state=="1"){
                  hButton.push(
                    h(
                      "el-button",
                      {
                        props: { type: "success", size: "small" },
                        style: { marginRight: "5px" },
                        on: {
                          click: () => {
                            this.addWarehouse(1,row);
                          }
                        }
                      },
                      "修改优先级"
                    )
                  );
                // }
                 
              return hButton;
            });
            }
          }
        }
      ],
      format: {
        to_task_id:{
          labelName: "任务列表",
          labelType: "select",
          labelValue:[],
        },
        before_or_after:{
          labelName: "位置",
          labelType: "radio",
          labelValue:[{key:1,value:"向前"},{key:2,value:"向后"}],
        }
      },
      ruleValidate: {
        // number_of_single: [{ required: true,message: "导出输量不能为空", trigger: "blur" }],
      },
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        this.initSearchData();
        this.onSearchGetList()
      }
    },
    async initSearchData(){
      let res = await Request.post("sys/country", "query_list");
      if (res.code == 0) {
        this.countrylistObj = {}
        this.countrylist = []
        if(res.code==0 && res.data != null){
            res.data.list.forEach((item) => {
            this.$set(this.countrylistObj,item.id,item.short_name+"_"+item.full_name)
            this.countrylist.push({id:item.id,name:item.short_name+"_"+item.full_name});
            })
        }
      }
      let res2 = await Request.post("customer/sieveConfig","query_list")//筛料源接口
      let label=''
      if(res2.code==0 && res2.data.length != 0){
        res2.data.list.forEach(res2 =>{
          label=res2.name=="sjb"?"数据吧":res2.name=='internal'?'自研':res2.name
          this.statuslist.push({id:res2.id,name:label+"("+res2.alias+")"})
        })
      }
    },
    dialogVisibleON(){
      this.dialogVisible=false
        this.timer = setInterval(() => {
            this.getList()
        }, this.dialogVisibleInput*1000)
        utils.showTip('自动刷新开启成功！');
    },
    flashSettimeout(){
      this.searchData.op = this._date
      if(this.flashvalue==true){
          this.dialogVisible=true
      }else{
        clearInterval(this.timer)
      }
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let sd = utils.cloneObj(this.searchData)
      //查询
      let res = await this.RequestPost("query_list",sd);
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data!=null) this.list = res.data.result.list;
        this.totalCnt = res.data.result.pagination.totalCnt
        this.format.to_task_id.labelValue = []
        if(this.list!==null&& res!==null){
          this.list.forEach((item,index) => {
          this.format.to_task_id.labelValue.push({id:item.id,name:item.id+"("+item.country+","+item.operator+","+index+")"})
        });
        }
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },
    //文件下载
    async addWarehouse(type,row){
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "修改优先级";
        info={
         from_task_id:row.id,
         to_task_id:'',
         before_or_after:1,
         op : "prioritise",
        }
      }
      this.onSelectChange("export_mode",info.export_mode);
      this.info=info
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,labelWidth:150,width:700,cancelBtnStatus:0},
        this.info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },
    //暂停启动终止
    async addWarehouse2(type,row,op,optitle){
      this.handleType = type;
        utils.showSureModal({
          "title":"提示",            
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认"+optitle+row.id+" ?","callBackArgs":{"op":op,task_id:row.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          console.log(data,"datadata")
          this.updateInfo(data);
        }
      });
    },
    onCheckChange(rows){
        this.selectRows = [];
        this.selectRows = rows;
        if(rows.records.length==0){
          this.selectRows = [];
        }
    },
     //导出列表
    async downloadFile() {
      let sd = utils.cloneObj(this.searchData)
      if (this.searchData.business_type === 4 && (this.searchData.warehouse_type == "" || this.searchData.warehouse_type == 17)) {
        sd.business_type = 1
        sd.warehouse_type = 17
      }
      if (this.searchData.business_type === 5 && (this.searchData.warehouse_type == "" || this.searchData.warehouse_type == 17)) {
        sd.business_type = 2
        sd.warehouse_type = 17
      }
      sd.op = "export"
      //查询
      let res = await this.RequestPost("query_list",sd);
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
            window.location.href = ACDN+res.data
        }else{
          utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":"导出异常",
          "title":"提示"});
        }
    },
    async updateInfo(info) {
     utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==4) {
        actionName = 'operate_items';
        tipText = '启动成功！';  
      }else if(this.handleType==3){
        actionName = 'operate_items';
        tipText = '暂停成功！';     
      }else if(this.handleType==2){
        actionName = 'operate_items';
        tipText = '终止成功！';
      }else if(this.handleType==1){
        actionName = 'operate_items';
        tipText = '修改权重成功';
      }    
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      console.log(res,"codecode");
      if (code === 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        if (res.data.code === 1){
          utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":res.data.message,
          "title":"提示"});
        }else{
          utils.showTip(tipText);
        }
        this.getList() 
      }
      
      utils.hideLoading();
        
    },
    //txt下载
    exportData2(url,name){
     const link = document.createElement("a");
      fetch(url)
      .then((res)=>res.blob())
      .then((blob)=>{
       link.href = URL.createObjectURL(blob)
       link.download = name
       document.body.appendChild(link)
       link.click()
        document.body.removeChild(link)
      })
     }
      ,
    //源文件下载
    async addSieveOpen(value){
      // utils.showLoading("正在生成中")
      let new_ids=""
      if(this.selectRows.checked==true && this.selectRows.records.length==1){
        this.addWarehouse(1,value)
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请选择一项 ",
         "title":"提示"});
      }
    },
    //批量导出文件下载（去重）
    async addSieveOpen2(value){
      // utils.showLoading("正在生成中")
      if (this.selectRows.length === 0) {
        utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
          "modalContent":"请至少选择一项 ",
          "title":"提示"})
          return
      }

      if(this.selectRows.records.length >= 1) {
        console.log("==========================", this.selectRows)
        let singleOrMore = this.selectRows.records.length > 1 ? "多" : "单"
        console.log("++++++++++++++++++++++++++", singleOrMore)
        return this.addWarehouse2(1, value, this.selectRows, singleOrMore)
      }
    },
    onChangePageSize(page,pageSize){
      this.modal = true
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    handleTabClick(tab) {
      this.searchData.op = tab.name;
      this._date =tab.name
      this.getList();
    },
    changeDate(){
      // this.searchTime.forEach((item,index)=>{
      //     let hour = item.split(":")[0]
      //     this.searchDate[index].setHours(hour);
      //     if(index==1){
      //       this.searchDate[index].setMinutes(59)
      //       this.searchDate[index].setSeconds(59)
      //     }
      //   })
      this.searchData.start = Date.parse(this.searchDate[0])/1000;
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400;
      this.onSearchGetList();
    },
    initDate(){
      let nowDay = ""
      let beginDay = nowDay;
      let endDay = nowDay;
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },
    slotHeader(h) {
    //   return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    //总计
    footerMethodFunc({ columns, data }){
      return [columns.map((item,index) => {
          if(index ==0){
            return '总计'
          }else if(['任务数'].includes(item.title)){
            return this.task_number
          }else if(['有效数'].includes(item.title)){
            return this.valid_number
          }
          return null
        })
      ]
    },
    filterPartner(item){
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1 ) return true
        return item.BusinessId==this.searchData.searchBusinessId;
    },
    filterChannel(item){
      if(this.searchData.searcPartnerId == undefined) {
        this.searchData.searcPartnerId = -1
      }
      if(this.searchData.searchBusinessId == undefined) {
        this.searchData.searchBusinessId = -1
      }

      if (item.Id == -1) return true;
      if ( this.searchData.searchBusinessId == -1 && this.searchData.searcPartnerId == -1 ) return true
      if ( this.searchData.searchBusinessId == -1 && this.searchData.searcPartnerId != -1 && item.PartnerId==this.searchData.searcPartnerId ) return true
      if ( this.searchData.searchBusinessId != -1 && this.searchData.searcPartnerId != -1 && item.PartnerId==this.searchData.searcPartnerId ) return true
      if ( this.searchData.searchBusinessId != -1 && this.searchData.searcPartnerId == -1 && item.BusinessId==this.searchData.searchBusinessId ) return true
    },
    async onSelectChange(label,value){
      this.format.number_of_single.labelHide = true;
       if(label=="export_mode"){
          if(value==1){
            this.format.number_of_single.labelHide = false;
          }
       }
    },
  },
  mounted() {
    bus.$on('linevalid',data =>{
        this.list=data
      })
  },
};
</script>